//
//  MeatCityKeeperViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/7/17.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#define cellH 188
#define mapViewMaxH [self fitSize:320]
#define mapViewMinH [self fitSize:150]

#import "MeatCityFriendsViewController.h"

#import "XXTGSearchAddressView.h"
#import "XXTGSearchAreaView.h"

#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>

#import "MeatCityFriendTableViewCell.h"
#import "MeaetCityFriendHeader.h"



@interface MeatCityFriendsViewController()<UITableViewDelegate, UITableViewDataSource ,UIScrollViewDelegate , CLLocationManagerDelegate, MKMapViewDelegate, AMapSearchDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, strong) CLLocation *useLocation; //当前地址
@property (nonatomic, strong) AMapPOI *aimMapPOI; //默认选择地址数据
@property (nonatomic, strong) AMapPOI *fristMapPOI; //定位地址数据

@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) XXTGSearchAddressView *searchAddressView; //搜索地址View
@property (nonatomic, strong) XXTGSearchAreaView *searchAreaView;

@property (nonatomic, strong) UIView *bottomView; //bottomView
@property (nonatomic, strong) UITableView *bottomTableView; //bottomTableView
@property (nonatomic, strong) UIImageView *bigPin; //大头针
@property (nonatomic, strong) UIButton *resetPositionIcon; //重新定位Icon
@property (nonatomic, strong) UITableViewCell *aimsCell; //默认选择的cell

@property (nonatomic, assign) BOOL isScroll; //是否滚动
@property (nonatomic, assign) BOOL isUpdateLocation; //是否更新位置
@property (nonatomic, assign) BOOL isFristPositioning; //是否是第一次定位
@property (nonatomic, assign) BOOL isDragPositioning; //是否拖拽定位
@property (nonatomic, assign) BOOL isChooseUpdateLocation; //是否选择更新位置

@property (nonatomic, assign) CGFloat mapViewH;
@property (nonatomic, assign) CGFloat keyboardHeight;

@property (nonatomic, strong) NSMutableArray *locations; //当前维度

@end


@implementation MeatCityFriendsViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavView];
    [self initSearch];
    [self initParams];
    [self addkeyBoardNotification];
}


- (void)setNavView
{
    self.view.backgroundColor = mBackgroudColor;
    
    self.isScroll = YES;
    self.isFristPositioning = YES;
    self.isDragPositioning = NO;
    self.isChooseUpdateLocation = YES;
    self.mapViewH = mapViewMaxH;
}

- (void)initParams
{
    //搜索地址View
//    [self.view addSubview:self.searchAddressView];
//     _searchAddressView.mj_y = 0;
    
    //bottomView
    [self.view insertSubview:self.bottomView atIndex:0];
    
    //[self.view addSubview:self.searchAreaView];
}


#pragma mark - response methods

- (void)didChickedResetLocation{

    _isUpdateLocation = YES;
    [self.locationManager startUpdatingLocation];
    //[self showHudWithMsg:@"重新定位中..."];
    //[self showProgressView];
}

#pragma mark - 显示用户附近信息
- (void)initSearch{
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
}

- (void)initSearchs{

    if (_useLocation == nil || _search == nil) {
        return;
    }

    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:self.useLocation.coordinate.latitude longitude:self.useLocation.coordinate.longitude];
    request.types = @"汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";
    request.sortrule = 0;
    // request.radius = 1000;
    // request.keywords = keywords;
    request.requireExtension = YES;
    [self.search AMapPOIAroundSearch:request];
}


- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{

    if (response.pois.count == 0) {
        return;
    }

    if (response.pois.count>0) {

        _locations = [response.pois mutableCopy];
        //[_locations addObject:self.fristMapPOI];
        //self.baseNavView.rightNavBtn.enabled = YES;

        kWeakSelf(self);
        [_locations enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

            AMapPOI *mapPoi = (AMapPOI *)obj;
            NSString *address = [NSString stringWithFormat:@"%@%@%@", mapPoi.city, mapPoi.district, mapPoi.address];
            mapPoi.address = address;

        }];

        dispatch_async(dispatch_get_main_queue(), ^{

            [weakself.bottomTableView reloadData];
        });
    }
}


#pragma mark -

- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated{

    if (!animated && !_isFristPositioning ) {
        self.isFristPositioning = YES;
    }
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{

    [self.locationManager stopUpdatingLocation];

    CLLocationCoordinate2D coordinate;
    coordinate.latitude = userLocation.location.coordinate.latitude;
    coordinate.longitude = userLocation.location.coordinate.longitude;


    if (_isUpdateLocation) {
        _isUpdateLocation = NO;
        //[self hideProgressView];
        [self setMapRegionWithCoordinate:coordinate];
    }
}


- (void)setMapRegionWithCoordinate:(CLLocationCoordinate2D)coordinate{

    MKCoordinateRegion region;
    region = MKCoordinateRegionMake(coordinate, MKCoordinateSpanMake(.01, .01));
    MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:region];
    _isFristPositioning = YES;
    [_mapView setRegion:adjustedRegion animated:YES];
}


//更新用户位置，只要用户改变则调用此方法（包括第一次定位到用户位置）
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated { // 调用获取中心点坐标代理方法

    [self.locationManager stopUpdatingLocation];

    MKCoordinateRegion region;
    CLLocationCoordinate2D centerCoordinate2D = mapView.region.center;
    region.center = centerCoordinate2D;

    if (self.isFristPositioning && _isChooseUpdateLocation) {

        self.isFristPositioning = NO;
        CLLocation *location = [[CLLocation alloc] initWithLatitude:centerCoordinate2D.latitude longitude:centerCoordinate2D.longitude];
        self.useLocation = location;

        CLGeocoder *geocoder = [[CLGeocoder alloc] init];

        kWeakSelf(self);
        [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {

            CLPlacemark *place = [placemarks firstObject];

            weakself.fristMapPOI = [[AMapPOI alloc] init];
            //            NSString *address = [NSString stringWithFormat:@"%@%@%@", place.locality, place.subLocality, place.name];
            //            weakself.fristMapPOI.address = address;
            //            weakself.fristMapPOI.location.latitude = place.location.coordinate.latitude;
            //            weakself.fristMapPOI.location.longitude = place.location.coordinate.longitude;
            //
            //            NSLog(@"%@%@%@%@",place.administrativeArea, place.locality, place.subLocality, place.name);
            //            NSLog(@"%@%@%lf%lf",place.thoroughfare, place.subLocality, place.location.coordinate.latitude, place.location.coordinate.latitude);
            //            NSLog(@"%@", weakself.fristMapPOI.address);



            //            weakself.currentProvince = [weakself checkIsNull:place.administrativeArea];
            //            weakself.currentCity = [weakself checkIsNull:place.locality];
            //            weakself.currentArea = [weakself checkIsNull:place.subLocality];
            //
            //            NSString *placename = [weakself checkIsNull:place.name];
            //            NSString *thoroughfare = [weakself checkIsNull:place.thoroughfare];
            //            NSString *subThoroughfare = [weakself checkIsNull:place.subThoroughfare];
            //
            //
            //            if ([place.name containsString: place.thoroughfare]) {
            //                weakself.row_three_textview.text = thoroughfare;
            //            }else{
            //                weakself.row_three_textview.text = [NSString stringWithFormat:@"%@%@%@",placename, thoroughfare, subThoroughfare];
            //            }

        }];


        [self initSearchs];
    }else{
        _isChooseUpdateLocation = YES;
    }

    [self bigPinAnimation];

}


//大头针跳动的动画
- (void)bigPinAnimation{

    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{

        CGPoint center = self.bigPin.center;
        center.y -= 20;
        [self.bigPin setCenter:center];

    } completion:nil];

    [UIView animateWithDuration:0.45 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{

        CGPoint center = self.bigPin.center;
        center.y += 20;
        [self.bigPin setCenter:center];

    } completion:nil];
}


#pragma mark - scrollview.delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.isScroll) {
        _mapViewH = mapViewMinH;
        CGFloat contentOffsetY = scrollView.contentOffset.y;
        
       // NSLog(@"______  %lf, ", contentOffsetY);
        CGFloat maxOffsetY = mapViewMaxH - mapViewMinH;  // 简单的代码，没有适配      iphoneX
        //NSLog(@"++++++  %lf, ", maxOffsetY);

        if (contentOffsetY <= maxOffsetY ) {

            self.bottomTableView.transform = CGAffineTransformMakeTranslation(0, - contentOffsetY);
            self.resetPositionIcon.transform = CGAffineTransformMakeTranslation(0, - contentOffsetY/2.0);
            self.mapView.transform = CGAffineTransformMakeTranslation(0, - contentOffsetY/2.0);

            self.bottomTableView.height = self.bottomView.height - contentOffsetY;

        }else{

            _isScroll = NO;
        }
    }
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;
{
    CGPoint point=scrollView.contentOffset;

    if (!self.isScroll) {

        _isScroll = YES;

        if (point.y <cellH/2.0) {
            _mapViewH = mapViewMaxH;
            self.bottomTableView.transform = CGAffineTransformMakeTranslation(0, 0);
            self.resetPositionIcon.transform = CGAffineTransformMakeTranslation(0, 0);
            self.mapView.transform = CGAffineTransformMakeTranslation(0, 0);
        }
    }
}

#pragma mark - tableview.delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _locations.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
        return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    return [[MeaetCityFriendHeader alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.00001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return indexPath == (_locations.count - 1) ?178 :188;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MeatCityFriendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CityShopkeeperListTableViewCell"];
    if (!cell) {
        cell = [[MeatCityFriendTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"CityShopkeeperListTableViewCell"];
    }

//    if (indexPath.row == 0) {
//        cell.accessoryType = UITableViewCellAccessoryCheckmark;
//        self.aimsCell = cell;
//    }else{
//        cell.accessoryType = UITableViewCellAccessoryNone;
//    }
//
//    cell.tintColor = mMainColor;
//    cell.textLabel.textColor = UIColorFromRGB(0x333333);
//    cell.detailTextLabel.textColor = UIColorFromRGB(0x999999);
//
//    AMapPOI *mapPOI = _locations[indexPath.row];
//
//    if (indexPath.row == 0) {
//        self.aimMapPOI = mapPOI;
//    }
//
//    cell.textLabel.text = [NSString stringWithFormat:@"%@", mapPOI.name];
//    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", mapPOI.address];

    return cell;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (self.aimsCell != nil) {
        self.aimsCell.accessoryType = UITableViewCellAccessoryNone;
    }

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    self.aimsCell = cell;

    if (indexPath.row < self.locations.count) {

        _isChooseUpdateLocation = NO;

        self.aimMapPOI = self.locations[indexPath.row];

        AMapGeoPoint *location = (AMapGeoPoint *)self.aimMapPOI.location;

        CLLocationCoordinate2D coordinate;
        coordinate.latitude = location.latitude;
        coordinate.longitude = location.longitude;


        [self setMapRegionWithCoordinate:coordinate];
    }
}


#pragma mark - setter and getter methods

//添加地图控件
- (MKMapView *)mapView{
    
    if (!_mapView) {
        
        _mapView = [[MKMapView alloc]initWithFrame:CGRectZero];
        _mapView.size = CGSizeMake(KScreenWidth, mapViewMaxH);
        _mapView.mj_x = 0;
        _mapView.mj_y = 0;
        _mapView.delegate = self;
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        
        if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse){
            [_locationManager requestWhenInUseAuthorization];
        }
        _mapView.userTrackingMode = MKUserTrackingModeFollow;
        _mapView.mapType = MKMapTypeStandard;
        
        //大头针
        [_mapView addSubview:self.bigPin];

        //重新定位Icon
        [_mapView addSubview:self.resetPositionIcon];
        _resetPositionIcon.mj_y = _mapView.height - _resetPositionIcon.width - 15;
        
    }
    return _mapView;
}

//大头针
- (UIImageView *)bigPin
{
    if (!_bigPin) {
        
        _bigPin = [[UIImageView alloc] init];
        _bigPin.image = [UIImage imageNamed:@"address_location"];
        _bigPin.size = CGSizeMake(20, 40);
        _bigPin.mj_x = KScreenWidth/2.0 - 10;
        _bigPin.mj_y = mapViewMaxH/2.0 - 40;
    }
    return _bigPin;
}


//重新定位Icon
- (UIButton *)resetPositionIcon
{
    if (!_resetPositionIcon) {
        _resetPositionIcon = [UIButton buttonWithType:UIButtonTypeCustom];
        [_resetPositionIcon setImage:[UIImage imageNamed:@"address_location_btn"] forState:UIControlStateNormal];
        _resetPositionIcon.size = CGSizeMake(56, 56);
        _resetPositionIcon.contentMode = UIViewContentModeCenter;
        _resetPositionIcon.mj_x = KScreenWidth - _resetPositionIcon.width - 5;
        [_resetPositionIcon addTarget:self action:@selector(didChickedResetLocation) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _resetPositionIcon;
}


//搜索地址View
- (XXTGSearchAddressView *)searchAddressView
{
    if (!_searchAddressView) {
        _searchAddressView = [[XXTGSearchAddressView alloc] init];
        
        
        kWeakSelf(self);
        //开始编辑Block
        _searchAddressView.startBlock = ^{
            
            // weakself.baseNavView.hidden = YES;
            weakself.searchAreaView.hidden = NO;
            //weakself.searchAddressView.mj_y = XXTG_StatusBarHeight_Define;
            weakself.bottomView.mj_y = weakself.searchAddressView.bottom;
            weakself.bottomView.height = KScreenHeight - weakself.searchAddressView.bottom ;
            weakself.bottomTableView.height = weakself.bottomView.height - _mapViewH;
            weakself.searchAreaView.mj_y = weakself.searchAddressView.bottom;
        };
        
        
        //结束编辑Block
        _searchAddressView.endBlock = ^{
            
            //weakself.baseNavView.hidden = NO;
            weakself.searchAreaView.hidden = YES;
            // weakself.searchAddressView.mj_y = weakself.baseNavView.bottom;
            weakself.bottomView.mj_y = weakself.searchAddressView.bottom;
            weakself.bottomView.height = KScreenHeight - weakself.searchAddressView.bottom;
            weakself.bottomTableView.height = weakself.bottomView.height - _mapViewH;
            
        };
    }
    return _searchAddressView;
    
}


//bottomView
- (UIView *)bottomView
{
    if (!_bottomView) {
        
        _bottomView = [[UIView alloc] init];
        _bottomView.mj_x = 0;
        _bottomView.mj_y = 0;
        _bottomView.size = CGSizeMake(KScreenWidth, KScreenHeight - 180 - TJ_TabBarHeight);
        _bottomView.backgroundColor = KWhiteColor;
        
        //地图
        [_bottomView addSubview:self.mapView];
        
        [_bottomView addSubview:self.bottomTableView];
        _bottomTableView.mj_y =  _mapViewH;
        _bottomTableView.height = _bottomView.height - _mapViewH;
        
    }
    return _bottomView;
}


//bottomTableView
- (UITableView *)bottomTableView
{
    if (!_bottomTableView) {
        _bottomTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _bottomTableView.delegate = self;
        _bottomTableView.dataSource = self;
        _bottomTableView.backgroundColor = KWhiteColor;
        _bottomTableView.separatorColor = KClearColor;
        _bottomTableView.mj_x = 0;
        _bottomTableView.width = KScreenWidth;
    }
    return _bottomTableView;
    
}


- (XXTGSearchAreaView *)searchAreaView{
    if (!_searchAreaView) {
        CGRect rect = CGRectMake(0, 0, KScreenWidth, KScreenHeight);
        _searchAreaView = [[XXTGSearchAreaView alloc]initWithFrame:rect];
        _searchAreaView.hidden = YES;
        
        kWeakSelf(self)
        _searchAreaView.choosedCellBlock = ^(NSInteger choosedIndex, AMapTip *tip) {
            
            weakself.searchAreaView.hidden = YES;
            [weakself.view endEditing:YES];
            AMapGeoPoint *location = (AMapGeoPoint *)tip.location;
            
            CLLocationCoordinate2D coordinate;
            coordinate.latitude = location.latitude;
            coordinate.longitude = location.longitude;
            
           // [weakself setMapRegionWithCoordinate:coordinate];
            
            [weakself.searchAreaView clearTableViewData];
            [weakself.searchAddressView cancelDealTextField];
        };
        
        
        _searchAreaView.tapGestureBlock = ^{
            weakself.searchAreaView.hidden = YES;
            [weakself.view endEditing:YES];
        };
        
    }
    return _searchAreaView;
}

#pragma mark - notification methods

- (void)keyboardWillShow:(NSNotification *)aNotification{
    
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    self.keyboardHeight = keyboardRect.size.height;
    self.searchAreaView.height = KScreenHeight - self.searchAddressView.bottom - self.keyboardHeight;
    
}

- (void)keyboardWillHide:(NSNotification *)aNotification{ //当键退出时调用
    
    self.keyboardHeight = 0.0;
    self.searchAreaView.height = KScreenHeight - self.searchAddressView.bottom - self.keyboardHeight;
}


- (void)textFieldTextChanged:(NSNotification *)aNotification
{
    UITextField * textField = aNotification.object;
    
    if (textField == self.searchAddressView.textField) {
        
        if (textField.text.length >0) {
            [self.searchAreaView keywordsSearchWithKeywords:textField.text];
            
        }else{
            [self.searchAreaView clearTableViewData];
        }
    }
}

#pragma mark - other methods

//添加键盘通知
- (void)addkeyBoardNotification{
    
    [kNotificationCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(textFieldTextChanged:) name:UITextFieldTextDidChangeNotification object:nil];
}

//移除键盘通知
- (void)removeKeyboardNotification{
    
    [kNotificationCenter removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [kNotificationCenter removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [kNotificationCenter removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)dealloc{
    
    [self removeKeyboardNotification];
}

@end
